<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Kafka," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言在上文 设计一个百万级的消息推送系统 中提到消息流转采用的是 Kafka 作为中间件。
其中有朋友咨询在大量消息的情况下 Kakfa 是如何保证消息的高效及一致性呢？
正好以这个问题结合 Kakfa 的源码讨论下如何正确、高效的发送消息。

内容较多，对源码感兴趣的朋友请系好安全带😏(源码基于 v0.10.0.0 版本分析)。同时最好是有一定的 Kafka 使用经验，知晓基本的用法。">
<meta property="og:type" content="article">
<meta property="og:title" content="从源码分析如何优雅的使用 Kafka 生产者">
<meta property="og:url" content="http://crossoverjie.top/2018/10/11/kafka/kafka-product/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言在上文 设计一个百万级的消息推送系统 中提到消息流转采用的是 Kafka 作为中间件。
其中有朋友咨询在大量消息的情况下 Kakfa 是如何保证消息的高效及一致性呢？
正好以这个问题结合 Kakfa 的源码讨论下如何正确、高效的发送消息。

内容较多，对源码感兴趣的朋友请系好安全带😏(源码基于 v0.10.0.0 版本分析)。同时最好是有一定的 Kafka 使用经验，知晓基本的用法。">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d10ebd53b.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d11527115.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d1166034a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d11748eb5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d118ac608.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d119c9164.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d11badd71.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d1216d13b.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d12228c9b.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d12331873.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d1242d911.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d12561bc2.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d12b5da80.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d12c3c202.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d12d27034.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d12e065fd.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d135e046c.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d13759e66.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d138711e9.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d1394ac36.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d13fc139d.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d141d52c5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d14327d87.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d14413679.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d1453fc23.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d1464d1b3.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d14dd3792.jpg">
<meta property="og:updated_time" content="2019-05-07T18:42:06.004Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="从源码分析如何优雅的使用 Kafka 生产者">
<meta name="twitter:description" content="前言在上文 设计一个百万级的消息推送系统 中提到消息流转采用的是 Kafka 作为中间件。
其中有朋友咨询在大量消息的情况下 Kakfa 是如何保证消息的高效及一致性呢？
正好以这个问题结合 Kakfa 的源码讨论下如何正确、高效的发送消息。

内容较多，对源码感兴趣的朋友请系好安全带😏(源码基于 v0.10.0.0 版本分析)。同时最好是有一定的 Kafka 使用经验，知晓基本的用法。">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1d10ebd53b.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2018/10/11/kafka/kafka-product/"/>

  <title> 从源码分析如何优雅的使用 Kafka 生产者 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                从源码分析如何优雅的使用 Kafka 生产者
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-10-11T00:02:24+08:00" content="2018-10-11">
              2018-10-11
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Kafka/" itemprop="url" rel="index">
                    <span itemprop="name">Kafka</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Kafka/Java-进阶/" itemprop="url" rel="index">
                    <span itemprop="name">Java 进阶</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/10/11/kafka/kafka-product/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/10/11/kafka/kafka-product/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/10/11/kafka/kafka-product/" class="leancloud_visitors" data-flag-title="从源码分析如何优雅的使用 Kafka 生产者">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1d10ebd53b.jpg" alt=""></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>在上文 <a href="https://crossoverjie.top/2018/09/25/netty/million-sms-push/">设计一个百万级的消息推送系统</a> 中提到消息流转采用的是 <code>Kafka</code> 作为中间件。</p>
<p>其中有朋友咨询在大量消息的情况下 <code>Kakfa</code> 是如何保证消息的高效及一致性呢？</p>
<p>正好以这个问题结合 <code>Kakfa</code> 的源码讨论下如何正确、高效的发送消息。</p>
<blockquote>
<p>内容较多，对源码感兴趣的朋友请系好安全带😏(源码基于 <code>v0.10.0.0</code> 版本分析)。同时最好是有一定的 Kafka 使用经验，知晓基本的用法。</p>
</blockquote>
<a id="more"></a>
<h1 id="简单的消息发送"><a href="#简单的消息发送" class="headerlink" title="简单的消息发送"></a>简单的消息发送</h1><p>在分析之前先看一个简单的消息发送是怎么样的。</p>
<blockquote>
<p>以下代码基于 SpringBoot 构建。</p>
</blockquote>
<p>首先创建一个 <code>org.apache.kafka.clients.producer.Producer</code> 的 bean。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d11527115.jpg" alt=""></p>
<p>主要关注 <code>bootstrap.servers</code>，它是必填参数。指的是 Kafka 集群中的 broker 地址，例如 <code>127.0.0.1:9094</code>。</p>
<blockquote>
<p>其余几个参数暂时不做讨论，后文会有详细介绍。</p>
</blockquote>
<p>接着注入这个 bean 即可调用它的发送函数发送消息。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d1166034a.jpg" alt=""></p>
<p>这里我给某一个 Topic 发送了 10W 条数据，运行程序消息正常发送。</p>
<p>但这仅仅只是做到了消息发送，对消息是否成功送达完全没管，等于是纯<code>异步</code>的方式。</p>
<h2 id="同步"><a href="#同步" class="headerlink" title="同步"></a>同步</h2><p>那么我想知道消息到底发送成功没有该怎么办呢？</p>
<p>其实 <code>Producer</code> 的 <code>API</code> 已经帮我们考虑到了，发送之后只需要调用它的 <code>get()</code> 方法即可同步获取发送结果。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d11748eb5.jpg" alt=""></p>
<p>发送结果：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d118ac608.jpg" alt=""></p>
<p>这样的发送效率其实是比较低下的，因为每次都需要同步等待消息发送的结果。 </p>
<h2 id="异步"><a href="#异步" class="headerlink" title="异步"></a>异步</h2><p>为此我们应当采取异步的方式发送，其实 <code>send()</code> 方法默认则是异步的，只要不手动调用  <code>get()</code> 方法。</p>
<p>但这样就没法获知发送结果。</p>
<p>所以查看 <code>send()</code> 的 API 可以发现还有一个参数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function">Future&lt;RecordMetadata&gt; <span class="title">send</span><span class="params">(ProducerRecord&lt;K, V&gt; producer, Callback callback)</span></span>;</div></pre></td></tr></table></figure>
<p><code>Callback</code> 是一个回调接口，在消息发送完成之后可以回调我们自定义的实现。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d119c9164.jpg" alt=""></p>
<p>执行之后的结果：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d11badd71.jpg" alt=""></p>
<p>同样的也能获取结果，同时发现回调的线程并不是上文同步时的<code>主线程</code>，这样也能证明是异步回调的。</p>
<p>同时回调的时候会传递两个参数：</p>
<ul>
<li><code>RecordMetadata</code> 和上文一致的消息发送成功后的元数据。</li>
<li><code>Exception</code> 消息发送过程中的异常信息。</li>
</ul>
<p>但是这两个参数并不会同时都有数据，只有发送失败才会有异常信息，同时发送元数据为空。</p>
<p>所以正确的写法应当是：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d1216d13b.jpg" alt=""></p>
<blockquote>
<p>至于为什么会只有参数一个有值，在下文的源码分析中会一一解释。</p>
</blockquote>
<h1 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h1><p>现在只掌握了基本的消息发送，想要深刻的理解发送中的一些参数配置还是得源码说了算。</p>
<p>首先还是来谈谈消息发送时的整个流程是怎么样的，<code>Kafka</code> 并不是简单的把消息通过网络发送到了 <code>broker</code> 中，在 Java 内部还是经过了许多优化和设计。</p>
<h2 id="发送流程"><a href="#发送流程" class="headerlink" title="发送流程"></a>发送流程</h2><p>为了直观的了解发送的流程，简单的画了几个在发送过程中关键的步骤。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d12228c9b.jpg" alt=""></p>
<p>从上至下依次是：</p>
<ul>
<li>初始化以及真正发送消息的 <code>kafka-producer-network-thread</code> IO 线程。</li>
<li>将消息序列化。</li>
<li>得到需要发送的分区。</li>
<li>写入内部的一个缓存区中。</li>
<li>初始化的 IO 线程不断的消费这个缓存来发送消息。</li>
</ul>
<h2 id="步骤解析"><a href="#步骤解析" class="headerlink" title="步骤解析"></a>步骤解析</h2><p>接下来详解每个步骤。</p>
<h3 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h3><p><img src="https://i.loli.net/2019/05/08/5cd1d12331873.jpg" alt=""></p>
<p>调用该构造方法进行初始化时，不止是简单的将基本参数写入 <code>KafkaProducer</code>。比较麻烦的是初始化 <code>Sender</code> 线程进行缓冲区消费。</p>
<p>初始化 IO 线程处：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d1242d911.jpg" alt=""></p>
<p>可以看到 Sender 线程有需要成员变量，比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">acks,retries,requestTimeout</div></pre></td></tr></table></figure>
<p>等，这些参数会在后文分析。</p>
<h3 id="序列化消息"><a href="#序列化消息" class="headerlink" title="序列化消息"></a>序列化消息</h3><p>在调用 <code>send()</code> 函数后其实第一步就是序列化，毕竟我们的消息需要通过网络才能发送到 Kafka。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d12561bc2.jpg" alt=""></p>
<p>其中的 <code>valueSerializer.serialize(record.topic(), record.value());</code> 是一个接口，我们需要在初始化时候指定序列化实现类。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d12b5da80.jpg" alt=""></p>
<p>我们也可以自己实现序列化，只需要实现 <code>org.apache.kafka.common.serialization.Serializer</code> 接口即可。</p>
<h3 id="路由分区"><a href="#路由分区" class="headerlink" title="路由分区"></a>路由分区</h3><p>接下来就是路由分区，通常我们使用的 <code>Topic</code> 为了实现扩展性以及高性能都会创建多个分区。</p>
<p>如果是一个分区好说，所有消息都往里面写入即可。</p>
<p>但多个分区就不可避免需要知道写入哪个分区。</p>
<p>通常有三种方式。</p>
<h4 id="指定分区"><a href="#指定分区" class="headerlink" title="指定分区"></a>指定分区</h4><p>可以在构建 <code>ProducerRecord</code> 为每条消息指定分区。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d12c3c202.jpg" alt=""></p>
<p>这样在路由时会判断是否有指定，有就直接使用该分区。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d12d27034.jpg" alt=""></p>
<p>这种一般在特殊场景下会使用。</p>
<h4 id="自定义路由策略"><a href="#自定义路由策略" class="headerlink" title="自定义路由策略"></a>自定义路由策略</h4><p><img src="https://i.loli.net/2019/05/08/5cd1d12e065fd.jpg" alt=""></p>
<p>如果没有指定分区，则会调用 <code>partitioner.partition</code> 接口执行自定义分区策略。</p>
<p>而我们也只需要自定义一个类实现 <code>org.apache.kafka.clients.producer.Partitioner</code> 接口，同时在创建 <code>KafkaProducer</code> 实例时配置 <code>partitioner.class</code> 参数。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d135e046c.jpg" alt=""></p>
<p>通常需要自定义分区一般是在想尽量的保证消息的顺序性。</p>
<p>或者是写入某些特有的分区，由特别的消费者来进行处理等。</p>
<h4 id="默认策略"><a href="#默认策略" class="headerlink" title="默认策略"></a>默认策略</h4><p>最后一种则是默认的路由策略，如果我们啥都没做就会执行该策略。</p>
<p>该策略也会使得消息分配的比较均匀。</p>
<p>来看看它的实现：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d13759e66.jpg" alt=""></p>
<p>简单的来说分为以下几步：</p>
<ul>
<li>获取 Topic 分区数。</li>
<li>将内部维护的一个线程安全计数器 +1。</li>
<li>与分区数取模得到分区编号。</li>
</ul>
<p>其实这就是很典型的轮询算法，所以只要分区数不频繁变动这种方式也会比较均匀。</p>
<h3 id="写入内部缓存"><a href="#写入内部缓存" class="headerlink" title="写入内部缓存"></a>写入内部缓存</h3><p>在 <code>send()</code> 方法拿到分区后会调用一个 <code>append()</code> 函数：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d138711e9.jpg" alt=""></p>
<p>该函数中会调用一个 <code>getOrCreateDeque()</code> 写入到一个内部缓存中 <code>batches</code>。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d1394ac36.jpg" alt=""></p>
<h3 id="消费缓存"><a href="#消费缓存" class="headerlink" title="消费缓存"></a>消费缓存</h3><p>在最开始初始化的 IO 线程其实是一个守护线程，它会一直消费这些数据。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d13fc139d.jpg" alt=""></p>
<p>通过图中的几个函数会获取到之前写入的数据。这块内容可以不必深究，但其中有个 <code>completeBatch</code> 方法却非常关键。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d141d52c5.jpg" alt=""></p>
<p>调用该方法时候肯定已经是消息发送完毕了，所以会调用 <code>batch.done()</code> 来完成之前我们在 <code>send()</code> 方法中定义的回调接口。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d14327d87.jpg" alt=""></p>
<blockquote>
<p>从这里也可以看出为什么之前说发送完成后元数据和异常信息只会出现一个。</p>
</blockquote>
<h1 id="Producer-参数解析"><a href="#Producer-参数解析" class="headerlink" title="Producer 参数解析"></a>Producer 参数解析</h1><p>发送流程讲完了再来看看 <code>Producer</code> 中比较重要的几个参数。</p>
<h2 id="acks"><a href="#acks" class="headerlink" title="acks"></a>acks</h2><p><code>acks</code> 是一个影响消息吞吐量的一个关键参数。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d14413679.jpg" alt=""></p>
<p>主要有 <code>[all、-1, 0, 1]</code> 这几个选项，默认为 1。</p>
<p>由于 <code>Kafka</code> 不是采取的主备模式，而是采用类似于 Zookeeper 的主备模式。</p>
<blockquote>
<p>前提是 <code>Topic</code> 配置副本数量 <code>replica &gt; 1</code>。 </p>
</blockquote>
<p>当 <code>acks = all/-1</code> 时：</p>
<p>意味着会确保所有的 follower 副本都完成数据的写入才会返回。</p>
<p>这样可以保证消息不会丢失！</p>
<blockquote>
<p>但同时性能和吞吐量却是最低的。</p>
</blockquote>
<p>当 <code>acks = 0</code> 时：</p>
<p>producer 不会等待副本的任何响应，这样最容易丢失消息但同时性能却是最好的！</p>
<p>当 <code>acks = 1</code> 时：</p>
<p>这是一种折中的方案，它会等待副本 Leader 响应，但不会等到 follower 的响应。</p>
<p>一旦 Leader 挂掉消息就会丢失。但性能和消息安全性都得到了一定的保证。</p>
<h2 id="batch-size"><a href="#batch-size" class="headerlink" title="batch.size"></a>batch.size</h2><p>这个参数看名称就知道是内部缓存区的大小限制，对他适当的调大可以提高吞吐量。</p>
<p>但也不能极端，调太大会浪费内存。小了也发挥不了作用，也是一个典型的时间和空间的权衡。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d1453fc23.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d1464d1b3.jpg" alt=""></p>
<p>上图是几个使用的体现。</p>
<h2 id="retries"><a href="#retries" class="headerlink" title="retries"></a>retries</h2><p><code>retries</code> 该参数主要是来做重试使用，当发生一些网络抖动都会造成重试。</p>
<p>这个参数也就是限制重试次数。</p>
<p>但也有一些其他问题。</p>
<ul>
<li>因为是重发所以消息顺序可能不会一致，这也是上文提到就算是一个分区消息也不会是完全顺序的情况。</li>
<li>还是由于网络问题，本来消息已经成功写入了但是没有成功响应给 producer，进行重试时就可能会出现<code>消息重复</code>。这种只能是消费者进行幂等处理。</li>
</ul>
<h1 id="高效的发送方式"><a href="#高效的发送方式" class="headerlink" title="高效的发送方式"></a>高效的发送方式</h1><p>如果消息量真的非常大，同时又需要尽快的将消息发送到 <code>Kafka</code>。一个 <code>producer</code> 始终会收到缓存大小等影响。</p>
<p>那是否可以创建多个 <code>producer</code> 来进行发送呢？</p>
<ul>
<li>配置一个最大 producer 个数。</li>
<li>发送消息时首先获取一个 <code>producer</code>，获取的同时判断是否达到最大上限，没有就新建一个同时保存到内部的 <code>List</code> 中，保存时做好同步处理防止并发问题。</li>
<li>获取发送者时可以按照默认的分区策略使用轮询的方式获取（保证使用均匀）。</li>
</ul>
<p>这样在大量、频繁的消息发送场景中可以提高发送效率减轻单个 <code>producer</code> 的压力。</p>
<h1 id="关闭-Producer"><a href="#关闭-Producer" class="headerlink" title="关闭 Producer"></a>关闭 Producer</h1><p>最后则是 <code>Producer</code> 的关闭，Producer 在使用过程中消耗了不少资源（线程、内存、网络等）因此需要显式的关闭从而回收这些资源。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d14dd3792.jpg" alt=""></p>
<p>默认的 <code>close()</code> 方法和带有超时时间的方法都是在一定的时间后强制关闭。</p>
<p>但在过期之前都会处理完剩余的任务。</p>
<p>所以使用哪一个得视情况而定。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>本文内容较多，从实例和源码的角度分析了 Kafka 生产者。</p>
<p>希望看完的朋友能有收获，同时也欢迎留言讨论。</p>
<p>不出意外下期会讨论 Kafka 消费者。</p>
<blockquote>
<p>如果对你有帮助还请分享让更多的人看到。</p>
</blockquote>
<p><strong>欢迎关注公众号一起交流：</strong></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Kafka/" rel="tag">#Kafka</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/09/wheel/cicada4/" rel="next" title="「造个轮子」——cicada 设计全局上下文">
                <i class="fa fa-chevron-left"></i> 「造个轮子」——cicada 设计全局上下文
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/15/SpringBoot/SpringBoot-tips/" rel="prev" title="分享几个 SpringBoot 实用的小技巧">
                分享几个 SpringBoot 实用的小技巧 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#简单的消息发送"><span class="nav-number">2.</span> <span class="nav-text">简单的消息发送</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#同步"><span class="nav-number">2.1.</span> <span class="nav-text">同步</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异步"><span class="nav-number">2.2.</span> <span class="nav-text">异步</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#源码分析"><span class="nav-number">3.</span> <span class="nav-text">源码分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#发送流程"><span class="nav-number">3.1.</span> <span class="nav-text">发送流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#步骤解析"><span class="nav-number">3.2.</span> <span class="nav-text">步骤解析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#初始化"><span class="nav-number">3.2.1.</span> <span class="nav-text">初始化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#序列化消息"><span class="nav-number">3.2.2.</span> <span class="nav-text">序列化消息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#路由分区"><span class="nav-number">3.2.3.</span> <span class="nav-text">路由分区</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#指定分区"><span class="nav-number">3.2.3.1.</span> <span class="nav-text">指定分区</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#自定义路由策略"><span class="nav-number">3.2.3.2.</span> <span class="nav-text">自定义路由策略</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#默认策略"><span class="nav-number">3.2.3.3.</span> <span class="nav-text">默认策略</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#写入内部缓存"><span class="nav-number">3.2.4.</span> <span class="nav-text">写入内部缓存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#消费缓存"><span class="nav-number">3.2.5.</span> <span class="nav-text">消费缓存</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Producer-参数解析"><span class="nav-number">4.</span> <span class="nav-text">Producer 参数解析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#acks"><span class="nav-number">4.1.</span> <span class="nav-text">acks</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#batch-size"><span class="nav-number">4.2.</span> <span class="nav-text">batch.size</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#retries"><span class="nav-number">4.3.</span> <span class="nav-text">retries</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#高效的发送方式"><span class="nav-number">5.</span> <span class="nav-text">高效的发送方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#关闭-Producer"><span class="nav-number">6.</span> <span class="nav-text">关闭 Producer</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">7.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2018/10/11/kafka/kafka-product/';
      var disqus_title = "从源码分析如何优雅的使用 Kafka 生产者";
      var disqus_url = 'http://crossoverjie.top/2018/10/11/kafka/kafka-product/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
